package open.tech.dawn.web.core.service.impl;

import cn.hutool.core.collection.CollUtil;
import open.tech.dawn.web.core.entity.LoginUser;
import open.tech.dawn.web.core.service.IAuthService;
import open.tech.dawn.web.core.service.IPermissionCheckService;
import open.tech.dawn.web.util.HttpKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * 权限自定义检查
 */
@Service
public class PermissionCheckServiceServiceImpl implements IPermissionCheckService {

    @Autowired
    private IAuthService authService;


    @Override
    public boolean check(String[] permissions) {
        LoginUser user = authService.getUser();
        if (null == user) {
            return false;
        }
        if (permissions == null) {
            return false;
        }
        for (String permission : permissions) {
            if (permission == null)
                continue;
            if (CollUtil.isNotEmpty(user.getPermissions())) {
                if (user.getPermissions().contains(permission)) {
                    return true;
                }
                for (String p : user.getPermissions()) {
                    if (p.startsWith("/")) {
                        if (p.matches(permission.replace("/**", "/.+").replace("/*", "/[^/]+"))) {
                            return true;
                        }
                    } else {
                        if (p.matches(permission.replace("-**", "-.+").replace("-*", "-[^-]+"))) {
                            return true;
                        }
                    }

                }
            }

        }
        return false;
    }


    @Override
    public boolean checkAll() {
        HttpServletRequest request = HttpKit.getRequest();
        String requestURI = request.getServletPath();
        return check(new String[]{requestURI});
    }

}
